const { environment } = require('../config/environment.js')

const baseURL = environment.baseURL + '/auto'

export const uploadMixins = {
	data() {
		return {}
	},
	methods: {
		// 单张图片上传
		async afterReadOnlyOne(file) {
			const { url, name } = file
			return this.uploadFilePromise(url, name)
		},

		// 多张图片上传
		afterReadMultiple(event) {
			const { file } = event
			const lists = [].concat(file)
			const resultPromise = []
			lists.forEach(e => {
				const { url, name } = e
				const itemPromise = this.uploadFilePromise(url, name)
				resultPromise.push(itemPromise)
			})
			return Promise.all(resultPromise)
		},

		uploadFilePromise(url, name) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: baseURL + '/common/upload',
					filePath: url,
					name: 'file',
					formData: { name: name },
					success: res => {
						resolve(JSON.parse(res.data))
					}
				})
			})
		},
	}
}
